package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryVo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-12-19
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> treeSelect(Long parentId) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, parentId);
        List<Category> categoryList = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList = categoryList.stream().peek(category -> {
                LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, category.getId());
                Long count = baseMapper.selectCount(categoryLambdaQueryWrapper);
                category.setHasChildren(count > 0);
            }).collect(Collectors.toList());
        }
        return categoryList;
    }

    @Override
    public List<CategoryVo> getLevelOneCategory() {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0);
        List<Category> categoryList = baseMapper.selectList(categoryLambdaQueryWrapper);
        return categoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());

    }

    @Override
    public List<CategoryVo> tree() {
        List<Category> allCategoryList = baseMapper.selectList(null);
        List<CategoryVo> categoryVoList = allCategoryList.stream().map(allCategory -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(allCategory, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        return buildTree(categoryVoList);
    }

    /**
     * 构建类别树
     * 从一个类别列表中构建一个树形结构的列表，用于表示层级关系
     *
     * @param categoryVoList 原始的类别列表，包含所有类别的信息
     * @return 返回构建好的类别树，即根类别及其子类别
     */
    private List<CategoryVo> buildTree(List<CategoryVo> categoryVoList) {
        // 创建一个空列表，用于存放最终构建的类别树
        ArrayList<CategoryVo> trees = new ArrayList<>();

        // 过滤出所有父类别（即父ID为0的类别）
        categoryVoList
                .stream()
                .filter(categoryVo -> categoryVo.getParentId() == 0)
                .forEach(categoryVo -> {
                    // 对每个父类别，查找并添加其子类别
                    CategoryVo rootCategoryVo = findAndAddChildren
                            (categoryVo, categoryVoList);
                    // 将构建好的父类别（包括其子类别）添加到类别树中
                    trees.add(rootCategoryVo);
                });
        // 返回构建完成的类别树
        return trees;
    }

    /**
     * 递归查找并添加子类别
     *
     * 本方法通过递归方式在给定的类别列表中查找当前类别的所有子类别，并将它们添加到当前类别中
     * 这是一个私有方法，旨在内部使用以构建类别树结构
     *
     * @param categoryVo 当前类别对象，用于查找其子类别
     * @param categoryVoList 包含所有类别的列表，用于搜索子类别
     * @return 递归地返回经过处理的类别对象，最终返回null，因为这个方法的主要目的是为了构建类别树结构，而不是返回一个修改后的对象
     */
    private CategoryVo findAndAddChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        // 遍历类别列表，过滤出父类别ID与当前类别ID相同的子类别
        categoryVoList
                .stream()
                .filter(node -> node.getParentId().longValue()
                                == categoryVo.getId().longValue())
                .forEach(node ->{
                    // 对每个子类别，递归调用本方法以查找其子类别
                    CategoryVo children = findAndAddChildren(node,categoryVoList);
                    categoryVo.getChildren().add(children);
                });

        return categoryVo;
    }


}
